package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.pojo.dto.AddFocusModeIndexSetDTO;
import com.xbongbong.paas.pojo.dto.FixDataJobDTO;
import com.xbongbong.paas.pojo.dto.IndexReverseSettingClassicModeDTO;
import com.xbongbong.paas.pojo.dto.IndexSettingClassicModeDTO;
import com.xbongbong.paas.pojo.dto.ReverseAddFocusModeIndexSetDTO;
import com.xbongbong.paas.pojo.dto.ReverseUpdateCategoryDTO;
import com.xbongbong.paas.pojo.dto.UpdateCategoryDTO;
import com.xbongbong.paas.script.pojo.IndexSetAddContentPojo;
import com.xbongbong.paas.script.pojo.dto.IndexSetScriptDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.domain.entity.ChartCategoryEntity;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.domain.entity.IndexSetEntity;
import com.xbongbong.pro.enums.BoardTypeEnum;
import com.xbongbong.pro.enums.RepairExplainEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.index.pojo.IndexBoardChartSavePojo;
import com.xbongbong.pro.index.pojo.IndexSetDataPojo;
import com.xbongbong.pro.statistic.constant.ChartConstant;
import com.xbongbong.pro.statistic.enums.ChartCategoryAliasEnum;
import com.xbongbong.pro.statistic.enums.ChartCategoryTypeEnum;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.model.ChartCategoryModel;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.model.ChartModel;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.model.IndexSetModel;
import com.xbongbong.saas.service.IndexService;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 应用模块名称<p>
 * 代码描述<p>
 * Company: 逍邦网络科技有限公司<p>
 *
 * @author chenshan
 * @version v1.0
 * @since 2019-11-25 14:33
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX+"/script/index")
public class IndexScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(IndexScriptController.class);

    /**
     * 指标最大数量
     */
    private static final int CHART_MAX_COUNT = 12;

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private IndexSetModel indexSetModel;
    @Resource
    private ChartCustomModel chartCustomModel;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private ChartModel chartModel;
    @Resource
    private ChartCategoryModel chartCategoryModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private IndexService indexService;

    /**
     * 修改公司首页看板设置　statisticsType
     * @param fixDataJobDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/fixIndexSet", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixIndexSet(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }

        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            // 获取所有公司
            corpidList = companyModel.getCorpidList();
        }

        if (CollectionsUtil.isEmpty(corpidList)) {
            return "没有需要更新的数据";
        }
        LOG.warn("fixIndexBoardSet begin");
        int index = 1;
        LOG.warn(corpidList.size() + "家公司");

        List<IndexSetEntity> list;
        Set<Long> customChartIdSet = new HashSet<>();

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());

        Map<String, Object> chartParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        chartParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        chartParam.put(StringConstant.COLUMNS, "id");
        for (String corpid : corpidList) {
            LOG.warn(index + "/" + corpidList.size());
            index++;

            param.put(StringConstant.CORPID, corpid);
            list = indexSetModel.findEntitys(param);

            // 查询自定义图表数据
            chartParam.put(StringConstant.CORPID, corpid);
            List<ChartEntity> customChartList = chartCustomModel.findEntitys(chartParam);
            customChartIdSet.clear();
            for (ChartEntity entity : customChartList) {
                customChartIdSet.add(entity.getId());
            }

            // 修改数据
            boolean updateFlag;
            Iterator<IndexSetEntity> iterator = list.listIterator();
            while (iterator.hasNext()) {
                IndexSetEntity setEntity = iterator.next();
                List<IndexSetDataPojo> setDbList = setEntity.getContentData().toJavaList(IndexSetDataPojo.class);
                // 是否需要更新
                updateFlag = false;
                for (IndexSetDataPojo dataPojo : setDbList) {
                    // 设置第一层statisticsType
                    boolean updateFlag1 = setFirstLayerStatisticsType(dataPojo, customChartIdSet);
                    // 设置第二层statisticsType
                    boolean updateFlag2 = setSecondLayerStatisticsType(dataPojo.getEnableList(), customChartIdSet);
                    boolean updateFlag3 = setSecondLayerStatisticsType(dataPojo.getDisableList(), customChartIdSet);
                    // 是否需要更新
                    updateFlag = updateFlag || updateFlag1 || updateFlag2 || updateFlag3;
                }

                if (updateFlag) {
                    JSONArray data = new JSONArray();
                    data.addAll(setDbList);
                    setEntity.setContentData(data);
                } else {
                    iterator.remove();
                }
            }

            // 更新数据
            if (CollectionsUtil.isNotEmpty(list)) {
                LOG.warn("该公司处理数据:{}", list.size());
                indexSetModel.updateBatch(list, corpid);
            } else {
                LOG.warn("该公司处理数据:0");
            }
        }

        LOG.warn("fixIndexBoardSet end");
        return "success";
    }


    @RequestMapping(value = "/newFixIndexSet", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String newFixIndexSet(@RequestBody @Valid IndexSetScriptDTO indexSetScriptDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(indexSetScriptDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }


        String corpid = indexSetScriptDTO.getCorpid();
        BoardTypeEnum boardTypeEnum = BoardTypeEnum.getByCode(indexSetScriptDTO.getBoardType());

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, indexSetScriptDTO.getCorpid());
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        if (CollectionsUtil.isNotEmpty(indexSetScriptDTO.getUserIds())) {
            param.put("userIdIn", indexSetScriptDTO.getUserIds());
        }
        if (Objects.nonNull(indexSetScriptDTO.getBoardType())) {
            param.put("boardType", indexSetScriptDTO.getBoardType());
        }
        RepairExplainEnum repairExplainEnum = RepairExplainEnum.getByCode(indexSetScriptDTO.getOperate());
//        if (RepairExplainEnum.ADD == repairExplainEnum) {
//            if (!(BoardTypeEnum.DINGTALK == boardTypeEnum ||
//                  BoardTypeEnum.WEB_LEFT == boardTypeEnum ||
//                  BoardTypeEnum.WEB_RIGHT == boardTypeEnum)) {
//                return "添加数据，boardType类型错误！";
//            }
//        }

        int count = indexSetModel.getEntitysCount(param);
        if (count <= BasicConstant.ZERO) {
            return "没有需要更新的数据";
        }



        List<IndexSetEntity> list = indexSetModel.findEntitys(param);

        switch (repairExplainEnum){
            case REPAIR:
                repairIndex(corpid, list);
                break;
            case DEL:
                clearIndexSet(corpid, list);
                break;
            case ADD:
                addIndexSet(corpid, list, indexSetScriptDTO.getAddData());
                break;
            default:
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001,"未知操作");
        }


        LOG.warn("fixIndexBoardSet end");
        return "success";
    }

    /***
     * 初始化首页看板，多加isPublish=1数据，生成时间如下，只处理这段时间生成数据的公司
     * pro环境：2022-1-6 20:40:00（1641472800）----2022-1-21 00:00:00（1642694400）
     * 多平台环境：2022-1-13 20:00:00（1642075200）----2022-1-21 00:00:00（1642694400）
     * @param fixDataJobDTO 入参
     * @param: br
     * @throws
     * @return java.lang.String
     * @author hongxiao
     * @date 2022-01-25 16:07
     * @since
     * @version
     */
    @RequestMapping(value = "/fixIndexSet/isPublish", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixIndexSetIsPublish(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }

        // 添加时间必传
        Long addTimeEnd = fixDataJobDTO.getAddTime();
        Long addTimeStart = fixDataJobDTO.getAddTimeStart();

        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = new ArrayList<>();
            // 获取所有公司
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("addTimeStart", addTimeStart);
            param.put("addTimeEnd", addTimeEnd);
            param.put(StringConstant.COLUMNS, "corpid");
            List<IndexSetEntity> list = indexSetModel.findEntitys(param);
            for (IndexSetEntity indexSetEntity : list) {
                corpidList.add(indexSetEntity.getCorpid());
            }
        }

        if (CollectionsUtil.isEmpty(corpidList)) {
            return "没有需要更新的数据";
        }
        LOG.warn("fixIndexBoardSet begin");
        int index = 1;
        LOG.warn(corpidList.size() + "家公司");

        List<IndexSetEntity> list;
        Set<Long> chartIdSet = new HashSet<>();
        List<IndexSetEntity> updateList = new ArrayList<>();
        // 首页param
        Map<String, Object> indexParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        indexParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());

        // 图表分类param
        Map<String, Object> categoryParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        categoryParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        categoryParam.put(StringConstant.COLUMNS, "id");
        categoryParam.put("typeIn", Arrays.asList(ChartCategoryTypeEnum.WEB_INDEX_RIGHT.getCode(), ChartCategoryTypeEnum.WEB_INDEX_LEFT.getCode()));
        // 图表param
        Map<String, Object> chartParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        chartParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        chartParam.put(StringConstant.COLUMNS, "id");
        for (String corpid : corpidList) {
            LOG.warn(index + "/" + corpidList.size());
            index++;

            indexParam.put(StringConstant.CORPID, corpid);
            list = indexSetModel.findEntitys(indexParam);

            // 查询分类
            categoryParam.put(StringConstant.CORPID, corpid);
            List<ChartCategoryEntity> categoryList = chartCategoryModel.findEntitys(categoryParam);
            List<Long> categoryIdIn = new ArrayList<>();
            for (ChartCategoryEntity categoryEntity : categoryList) {
                categoryIdIn.add(categoryEntity.getId());
            }
            chartParam.put(StringConstant.CORPID, corpid);
            chartParam.put("categoryIdIn", categoryIdIn);
            List<ChartEntity> chartList = chartModel.findEntitys(chartParam);
            chartIdSet.clear();
            for (ChartEntity entity : chartList) {
                chartIdSet.add(entity.getId());
            }

            // 修改数据
            boolean updateFlag;
            updateList.clear();
            for (IndexSetEntity setEntity : list) {
                List<IndexSetDataPojo> setDbList = setEntity.getContentData().toJavaList(IndexSetDataPojo.class);
                // 是否需要更新
                updateFlag = false;
                Iterator<IndexSetDataPojo> iterator = setDbList.listIterator();
                while (iterator.hasNext()) {
                    IndexSetDataPojo dataPojo = iterator.next();
                    boolean removeFlag = Objects.equals(ChartConstant.CHART_CATEGORY_TYPE_CHART, dataPojo.getChartCategoryType())
                            && Objects.equals(StatisticsTypeEnum.SYSTEM_STATISTIC.getCode(), dataPojo.getStatisticsType())
                            && chartIdSet.contains(dataPojo.getChartCategoryId());
                    if (removeFlag) {
                        updateFlag = true;
                        iterator.remove();
                    }
                }
                if (updateFlag) {
                    JSONArray data = new JSONArray();
                    data.addAll(setDbList);
                    setEntity.setContentData(data);
                    updateList.add(setEntity);
                }
            }

            // 更新数据
            if (CollectionsUtil.isNotEmpty(updateList)) {
                LOG.warn("该公司处理数据:{}", updateList.size());
                indexSetModel.updateBatch(updateList, corpid);
            } else {
                LOG.warn("该公司处理数据:0");
            }
        }

        LOG.warn("fixIndexBoardSet end");
        return "success";
    }

    /**
     * 设置首页看板外层的statisticsType值，1系统，2自定义
     * chartCategoryType值，1分类，2指标
     * 分类时，statisticsType设置为1系统
     *
     * @param dataPojo 看板第一层设置pojo
     * @param customChartIdSet 自定义指标idSet
     */
    private boolean setFirstLayerStatisticsType(IndexSetDataPojo dataPojo, Set<Long> customChartIdSet) {
        if (Objects.nonNull(dataPojo.getStatisticsType())) {
            return false;
        }

        // id类型为指标且自定义指标id中包含设置statisticsType为自定义
        if (Objects.equals(ChartConstant.CHART_CATEGORY_TYPE_CHART, dataPojo.getChartCategoryType()) && customChartIdSet.contains(dataPojo.getChartCategoryId())) {
            dataPojo.setStatisticsType(StatisticsTypeEnum.CUSTOM_STATISTIC.getCode());
        } else {
            dataPojo.setStatisticsType(StatisticsTypeEnum.SYSTEM_STATISTIC.getCode());
        }
        return true;
    }

    /**
     * 设置首页看板几个字层的statisticsType值，1系统，2自定义
     * 第二层只有指标，直接判断是否包含在自定义指标中
     *
     * @param childList 看板第二层设置pojo
     * @param customChartIdSet 自定义指标idSet
     */
    private boolean setSecondLayerStatisticsType(List<IndexBoardChartSavePojo> childList, Set<Long> customChartIdSet) {
        if (CollectionsUtil.isEmpty(childList)) {
            return false;
        }
        boolean updateFlag = false;
        for (IndexBoardChartSavePojo savePojo : childList) {
            if (Objects.nonNull(savePojo.getStatisticsType())) {
                continue;
            }
            if (customChartIdSet.contains(savePojo.getId())) {
                savePojo.setStatisticsType(StatisticsTypeEnum.CUSTOM_STATISTIC.getCode());
            } else {
                savePojo.setStatisticsType(StatisticsTypeEnum.SYSTEM_STATISTIC.getCode());
            }
            updateFlag = true;
        }
        return updateFlag;
    }

    /**
     * 给现有公司是否有经典模式配置赋值1
     * @param indexSettingClassicModeDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/settingClassicModeDefault", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String settingClassicModeDefault(@RequestBody @Valid IndexSettingClassicModeDTO indexSettingClassicModeDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(indexSettingClassicModeDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }

        // 获取所有公司
        List<String> corpidList = indexSettingClassicModeDTO.getCorpidList();
        if (null == corpidList){
            corpidList = companyModel.getCorpidList();
        }
        corpidList = (null != corpidList) ? corpidList:new ArrayList<>();

        // 获取有模式设置的所有公司
        List<String> configCorpidList = companyConfigModel.getByAliasAllCorpids(CompanyConfigEnum.MOBILE_INDEX_MODE.getAlias());
        configCorpidList = (null != configCorpidList) ? configCorpidList : new ArrayList<>();

        // 去除设置过的公司
        corpidList.removeAll(configCorpidList);

        if (CollectionsUtil.isEmpty(corpidList)) {
            return "没有需要更新的数据";
        }
        LOG.warn("settingClassicModeDefault begin");
        LOG.warn(corpidList.size() + "家公司");
        String configName = CompanyConfigEnum.MOBILE_INDEX_MODE.getName();
        String configAlias = CompanyConfigEnum.MOBILE_INDEX_MODE.getAlias();
        String configValue = "[0,1]";
        List<CompanyConfigEntity> insertList = new ArrayList<>();
        Integer pageSize = 100;
        for (String corpid : corpidList) {
            CompanyConfigEntity companyConfigEntity = new CompanyConfigEntity(corpid, configName, configAlias, configValue);
            insertList.add(companyConfigEntity);
            if (insertList.size() >= pageSize) {
                if (CollectionsUtil.isNotEmpty(insertList)) {
                    companyConfigModel.insertBatch(insertList);
                    insertList.clear();
                }
            }
        }
        if (CollectionsUtil.isNotEmpty(insertList)) {
            companyConfigModel.insertBatch(insertList);
        }

        LOG.warn("settingClassicModeDefault over");
        return "success";
    }

    /**
     * 回滚给现有公司是否有经典模式配置赋值1
     * @param indexReverseSettingClassicModeDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/reverseSettingClassicModeDefault", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String reverseSettingClassicModeDefault(@RequestBody @Valid IndexReverseSettingClassicModeDTO indexReverseSettingClassicModeDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(indexReverseSettingClassicModeDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }

        // 获取有经典模式设置的所有公司
        List<String> corpidList = companyConfigModel.getByAliasAllCorpids(CompanyConfigEnum.MOBILE_INDEX_MODE.getAlias());
        corpidList = (null != corpidList) ? corpidList : new ArrayList<>();

        if (CollectionsUtil.isEmpty(corpidList)) {
            return "没有需要更新的数据";
        }
        LOG.warn("reverseSettingClassicModeDefault begin");
        LOG.warn(corpidList.size() + "家公司");
        String configAlias = CompanyConfigEnum.MOBILE_INDEX_MODE.getAlias();
        Integer pageSize = 100;
        int insertSize = corpidList.size();
        Integer pageNum = insertSize / pageSize + 1;
        LOG.info("开始刷脚本："+insertSize);
        for (int i = 1; i < pageNum + 1; i++) {
            Integer start = (i - 1) * pageSize;
            Integer end = i * pageSize;
            end = end > insertSize ? insertSize : end;
            List<String> subList = corpidList.subList(start,end);
            // 分页循环
            if (CollectionUtils.isNotEmpty(subList)){
                companyConfigModel.deleteBatchByCorpids4Script(subList,configAlias);
            }
        }

        LOG.warn("reverseSettingClassicModeDefault over");
        return "success";
    }

    /**
     * 给现有公司级以及用户级的首页配置加上专注模式
     * @param addFocusModeIndexSetDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addFocusModeIndexSet", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addFocusModeIndexSet(@RequestBody @Valid AddFocusModeIndexSetDTO addFocusModeIndexSetDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(addFocusModeIndexSetDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }

        // 获取所有公司
        List<String> corpidList = addFocusModeIndexSetDTO.getCorpidList();
        if (null == corpidList){
            corpidList = companyModel.getCorpidList();
        }
        corpidList = (null != corpidList) ? corpidList : new ArrayList<>();

        if (CollectionsUtil.isEmpty(corpidList)) {
            return "没有需要更新的数据";
        }
        LOG.warn("addFocusModeIndexSet begin");
        LOG.warn(corpidList.size() + "家公司");

        // 查出index_set表里面移动端的数据
        HashMap<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("boardType", BoardTypeEnum.DINGTALK.getCode());
        param.put("del",DelEnum.NORMAL.getDel());
        param.put("notEqualCustom",1);

        // 查出每个公司的右侧看板的categoryId
        List<String> dingTalkRightAlias = indexService.getDingTalkRightAlias();
        HashMap<String,Object> categoryParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        categoryParam.put("del",DelEnum.NORMAL.getDel());
        categoryParam.put("aliasIn",dingTalkRightAlias);
        categoryParam.put("columns","id");

        // 查每个公司里面有专注模式的用户
        HashMap<String,Object> indexParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        indexParam.put("del",DelEnum.NORMAL.getDel());
        indexParam.put("boardType",BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode());
        indexParam.put("columns","user_id");
        indexParam.put("notEqualCustom",1);

        // 要插入到index_set表的数据
        List<IndexSetEntity> insertList = new ArrayList<>();

        Integer pageSize = 100;
        int corpidListSize = corpidList.size();
        Integer corpidPageNum = corpidListSize / pageSize + 1;

        LOG.info("开始刷脚本："+corpidListSize);
        for (int i = 1; i < corpidPageNum + 1; i++) {
            Integer start = (i - 1) * pageSize;
            Integer end = i * pageSize;
            end = end > corpidListSize ? corpidListSize : end;
            List<String> subList = corpidList.subList(start,end);
            if (CollectionUtils.isEmpty(subList)){
                continue;
            }

            // 查出公司子集合的右侧看板的categoryId，并且用map存，key为corpid，value为此公司的右侧看板id
            HashMap<String,List<Long>> corpIdRightCategoryIdList = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            // 查出公司里面有专注模式的用户（crm默认首页）
            HashMap<String,List<String>> corpidHasFocusModeUserIds = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (String corpid : subList) {
                categoryParam.put("corpid", corpid);
                List<ChartCategoryEntity> chartCategoryEntityList = chartCategoryModel.findEntitys(categoryParam);
                if (CollectionUtils.isNotEmpty(chartCategoryEntityList)) {
                    List<Long> categoryList = chartCategoryEntityList.stream().map(e -> e.getId()).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(categoryList)){
                        corpIdRightCategoryIdList.put(corpid, categoryList);
                    }
                }

                indexParam.put("corpid", corpid);
                List<IndexSetEntity> indexSetEntityList = indexSetModel.findEntitys(indexParam);
                if (CollectionUtils.isNotEmpty(indexSetEntityList)){
                    List<String> userList = indexSetEntityList.stream().map(e -> e.getUserId()).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(userList)){
                        corpidHasFocusModeUserIds.put(corpid,userList);
                    }
                }
            }

            // 查出corpid在subList内index_set表里面移动端的数据
            param.put("corpidIn",subList);
            List<IndexSetEntity> indexSetEntityList = indexSetModel.findEntitys(param);
            // 分页循环
            if (CollectionUtils.isNotEmpty(indexSetEntityList)){
                for (IndexSetEntity indexSetEntity : indexSetEntityList) {
                    IndexSetEntity insertWorkEntity = new IndexSetEntity(indexSetEntity.getCorpid(),indexSetEntity.getUserId(),BoardTypeEnum.FOCUS_DINGTALK_WORK.getCode());
                    insertWorkEntity.setCustomPageFlag(null);
                    IndexSetEntity insertCategoryEntity = new IndexSetEntity(indexSetEntity.getCorpid(),indexSetEntity.getUserId(),BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode());
                    insertCategoryEntity.setCustomPageFlag(null);
                    List<IndexSetDataPojo> workPojoList = new ArrayList<>();
                    List<IndexSetDataPojo> categoryPojoList = new ArrayList<>();
                    if (indexSetEntity != null) {
                        List<IndexSetDataPojo> list;
                        try {
                            list = indexSetEntity.getContentData().toJavaList(IndexSetDataPojo.class);
                        } catch (JSONException e) {
                            list = null;
                        }
                        if (CollectionUtils.isNotEmpty(list)) {
                            List<Long> categoryList = corpIdRightCategoryIdList.get(indexSetEntity.getCorpid());
                            List<String> userIds = corpidHasFocusModeUserIds.get(indexSetEntity.getCorpid());
                            userIds = null == userIds ? new ArrayList<>() : userIds;
                            if (CollectionUtils.isEmpty(categoryList) || userIds.contains(indexSetEntity.getUserId())){
                                // TODO 加入失败集合
                                continue;
                            }
                            list.forEach(dataPojo -> {
                                if (categoryList.contains(dataPojo.getChartCategoryId())){
                                    workPojoList.add(dataPojo);
                                }else {
                                    categoryPojoList.add(dataPojo);
                                }
                            });
                            insertWorkEntity.setContentData(JSON.parseArray(JSONObject.toJSONString(workPojoList)));
                            insertCategoryEntity.setContentData(JSON.parseArray(JSONObject.toJSONString(categoryPojoList)));
                            insertList.add(insertWorkEntity);
                            insertList.add(insertCategoryEntity);
                        }
                    }
                }
            }
            if (insertList.size() >= pageSize || i == corpidPageNum){
                if (CollectionsUtil.isNotEmpty(insertList)){
                    indexSetModel.insertBatch(insertList);
                    insertList.clear();
                }
            }
        }

        LOG.warn("addFocusModeIndexSet over");
        return "success";
    }

    /**
     * 回滚给现有公司级以及用户级的首页配置加上专注模式
     * @param reverseAddFocusModeIndexSetDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/reverseAddFocusModeIndexSet", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String reverseAddFocusModeIndexSet(@RequestBody @Valid ReverseAddFocusModeIndexSetDTO reverseAddFocusModeIndexSetDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(reverseAddFocusModeIndexSetDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }

        // 获取所有公司
        List<String> corpidList = reverseAddFocusModeIndexSetDTO.getCorpidList();
        if (null == corpidList){
            corpidList = companyModel.getCorpidList();
        }
        corpidList = (null != corpidList) ? corpidList : new ArrayList<>();

        if (CollectionsUtil.isEmpty(corpidList)) {
            return "没有需要更新的数据";
        }
        LOG.warn("reverseAddFocusModeIndexSetDTO begin");
        LOG.warn(corpidList.size() + "家公司");
        Integer pageSize = 100;
        int insertSize = corpidList.size();
        Integer pageNum = insertSize / pageSize + 1;
        LOG.info("开始刷脚本："+insertSize);
        for (int i = 1; i < pageNum + 1; i++) {
            Integer start = (i - 1) * pageSize;
            Integer end = i * pageSize;
            end = end > insertSize ? insertSize : end;
            List<String> subList = corpidList.subList(start,end);
            // 分页循环
            if (CollectionUtils.isNotEmpty(subList)){
                indexService.deleteFocusBatchByCorpids4Script(subList);
            }
        }

        LOG.warn("reverseSettingClassicModeDefault over");
        return "success";
    }


    /**
     * 给现有公司级的分类里面待处理审批改成待我审批，审批进展改成我提交的，更新公告逻辑删除
     * @param updateCategoryDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateCategory", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateCategory(@RequestBody @Valid UpdateCategoryDTO updateCategoryDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(updateCategoryDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }

        // 获取所有公司
        List<String> corpidList = updateCategoryDTO.getCorpidList();
        if (null == corpidList){
            corpidList = companyModel.getCorpidList();
            // 加上corpid为0的公司
            corpidList.add("0");
        }
        corpidList = (null != corpidList) ? corpidList : new ArrayList<>();

        if (CollectionsUtil.isEmpty(corpidList)) {
            return "没有需要更新的数据";
        }

        LOG.warn("updateCategory begin");
        LOG.warn(corpidList.size() + "家公司");

        Integer pageSize = 100;
        int corpidListSize = corpidList.size();
        Integer corpidPageNum = corpidListSize / pageSize + 1;

        HashMap<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("aliasIn", Arrays.asList(ChartCategoryAliasEnum.APPROVAL.getAlias(),ChartCategoryAliasEnum.APPROVAL_PROGRESS.getAlias(),ChartCategoryAliasEnum.ANNOUNCEMENT.getAlias()));
        param.put("del",DelEnum.NORMAL.getDel());

        LOG.info("开始刷脚本："+corpidListSize);
        for (int i = 1; i < corpidPageNum + 1; i++) {
            Integer start = (i - 1) * pageSize;
            Integer end = i * pageSize;
            end = end > corpidListSize ? corpidListSize : end;
            List<String> subList = corpidList.subList(start,end);
            if (CollectionUtils.isEmpty(subList)){
                continue;
            }
            param.put("corpidIn",subList);
            List<ChartCategoryEntity> chartCategoryEntityList = chartCategoryModel.findEntitys(param);
            if (CollectionUtils.isEmpty(chartCategoryEntityList)){
                continue;
            }
            chartCategoryEntityList.forEach(item ->{
                ChartCategoryAliasEnum categoryAliasEnum = ChartCategoryAliasEnum.getByAlias(item.getAlias());
                switch (categoryAliasEnum){
                    case APPROVAL:
                    case APPROVAL_PROGRESS:
                        item.setName(categoryAliasEnum.getName());
                        item.setNameEn(categoryAliasEnum.getNameEn());
                        break;
                    case ANNOUNCEMENT:
                        item.setDel(DelEnum.DELETE.getDel());
                        break;
                }
            });
            chartCategoryModel.updateBatch4Script(chartCategoryEntityList,subList);
        }
        LOG.warn("updateCategory over");
        return "success";
    }

    /**
     * 回滚给现有公司级的分类里面待处理审批改成待我审批，审批进展改成我提交的，更新公告逻辑删除
     * @param reverseUpdateCategoryDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/reverseUpdateCategory", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String reverseUpdateCategory(@RequestBody @Valid ReverseUpdateCategoryDTO reverseUpdateCategoryDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(reverseUpdateCategoryDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }

        // 获取所有公司
        List<String> corpidList = reverseUpdateCategoryDTO.getCorpidList();
        if (null == corpidList){
            corpidList = companyModel.getCorpidList();
            // 加上corpid为0的公司
            corpidList.add("0");
        }
        corpidList = (null != corpidList) ? corpidList : new ArrayList<>();

        if (CollectionsUtil.isEmpty(corpidList)) {
            return "没有需要更新的数据";
        }

        LOG.warn("reverseUpdateCategory begin");
        LOG.warn(corpidList.size() + "家公司");

        Integer pageSize = 100;
        int corpidListSize = corpidList.size();
        Integer corpidPageNum = corpidListSize / pageSize + 1;

        HashMap<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("aliasIn", Arrays.asList(ChartCategoryAliasEnum.APPROVAL.getAlias(),ChartCategoryAliasEnum.APPROVAL_PROGRESS.getAlias(),ChartCategoryAliasEnum.ANNOUNCEMENT.getAlias()));
        String oldApprovalName = "待处理审批";
        String oldApprovalNameEn = "Pending approval";
        String oldApprovalProgressName = "审批进展";
        String oldApprovalProgressNameEn = "Approval progress";

        LOG.info("开始刷脚本："+corpidListSize);
        for (int i = 1; i < corpidPageNum + 1; i++) {
            Integer start = (i - 1) * pageSize;
            Integer end = i * pageSize;
            end = end > corpidListSize ? corpidListSize : end;
            List<String> subList = corpidList.subList(start,end);
            if (CollectionUtils.isEmpty(subList)){
                continue;
            }
            param.put("corpidIn",subList);
            List<ChartCategoryEntity> chartCategoryEntityList = chartCategoryModel.findEntitys(param);
            if (CollectionUtils.isEmpty(chartCategoryEntityList)){
                continue;
            }
            chartCategoryEntityList.forEach(item ->{
                ChartCategoryAliasEnum categoryAliasEnum = ChartCategoryAliasEnum.getByAlias(item.getAlias());
                switch (categoryAliasEnum){
                    case APPROVAL:
                        item.setName(oldApprovalName);
                        item.setNameEn(oldApprovalNameEn);
                        break;
                    case APPROVAL_PROGRESS:
                        item.setName(oldApprovalProgressName);
                        item.setNameEn(oldApprovalProgressNameEn);
                        break;
                    case ANNOUNCEMENT:
                        item.setDel(DelEnum.NORMAL.getDel());
                        break;
                }
            });
            chartCategoryModel.updateBatch4Script(chartCategoryEntityList,subList);
        }
        LOG.warn("reverseUpdateCategory over");
        return "success";
    }

    /***
     * 修复首页看板设置
     *
     * @param corpid 公司corpid
     * @param: list 首页看板设置
     * @throws
     * @return void
     * @author hongxiao
     * @date 2022-08-29 14:17
     * @since
     * @version
     */
    private void repairIndex(String corpid, List<IndexSetEntity> list) throws XbbException {
        // 查询公司图表分类
        Map<String, Object> categoryParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        categoryParam.put(StringConstant.CORPID, corpid);
        categoryParam.put(StringConstant.DEL , DelEnum.NORMAL.getDel());
        // 开启的状态
        categoryParam.put("enable", BasicConstant.ONE);
        // 首页所需图表类型
        List<Integer> typeInHome = ChartCategoryTypeEnum.getCodeList4Home();
        categoryParam.put("typeIn", typeInHome);
        List<ChartCategoryEntity> allCategoryList = chartCategoryModel.findEntitys(categoryParam);

        // 获取公司图表
        Map<String, Object> chartParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        chartParam.put(StringConstant.CORPID, corpid);
        chartParam.put(StringConstant.DEL , DelEnum.NORMAL.getDel());
        chartParam.put("publish" , BasicConstant.ONE);
        chartParam.put(StringConstant.COLUMNS, "id,category,statistics_type,enable,chart_type,explains");
        List<ChartEntity> allChartList = chartModel.findEntitys(chartParam);
        List<ChartEntity> allCustomChartList = chartCustomModel.findEntitys(chartParam);

        Map<Long, ChartCategoryEntity> categoryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, ChartEntity> systemChartMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, ChartEntity> customChartMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        allCategoryList.forEach(item -> categoryMap.put(item.getId(), item));
        allChartList.forEach(item -> systemChartMap.put(item.getId(), item));
        allCustomChartList.forEach(item -> customChartMap.put(item.getId(), item));

        // 修复数据
        for (IndexSetEntity setEntity : list) {
            // 非系统配置（userId=0）标识
            boolean nonCompanyConfig = !Objects.equals(BasicConstant.ZERO_STRING, setEntity.getUserId());
            List<IndexSetDataPojo> setDbList = setEntity.getContentData().toJavaList(IndexSetDataPojo.class);
            Iterator<IndexSetDataPojo> iterator = setDbList.listIterator();
            while (iterator.hasNext()) {
                IndexSetDataPojo dataPojo = iterator.next();
                if (Objects.isNull(dataPojo.getChartCategoryId())) {
                    iterator.remove();
                    continue;
                }
                // 图表
                if (Objects.nonNull(dataPojo.getChartCategoryType()) && Objects.equals(dataPojo.getChartCategoryType(), ChartConstant.CHART_CATEGORY_TYPE_CHART)) {
                    // 首页看板中的图表id不存在
                    if (!systemChartMap.containsKey(dataPojo.getChartCategoryId()) && !customChartMap.containsKey(dataPojo.getChartCategoryId())) {
                        iterator.remove();
                        continue;
                    }
                    // 获取图表
                    ChartEntity chartEntity = null;
                    if (Objects.equals(StatisticsTypeEnum.CUSTOM_STATISTIC.getCode(), dataPojo.getStatisticsType())) {
                        chartEntity = customChartMap.get(dataPojo.getChartCategoryId());
                    }else if (Objects.equals(StatisticsTypeEnum.SYSTEM_STATISTIC.getCode(), dataPojo.getStatisticsType())) {
                        chartEntity = systemChartMap.get(dataPojo.getChartCategoryId());
                    }
                    if (Objects.isNull(chartEntity)) {
                        iterator.remove();
                        continue;
                    }

                    // 无指标
                    dataPojo.getEnableList().clear();
                    dataPojo.getDisableList().clear();
                    // secondCategoryId
                    List<Long> cidList = chartEntity.getCategory().toJavaList(Long.class);
                    dataPojo.setSecondCategoryId(cidList.get(0));
                    dataPojo.setStatisticsType(chartEntity.getStatisticsType());
                    dataPojo.setEnable(chartEntity.getEnable());
                    dataPojo.setShowType(chartEntity.getChartType());
                    dataPojo.setSort(BasicConstant.ZERO);

                    // 移动端是否隐藏，自定义图表
                    JSONObject explains = chartEntity.getExplains();
                    if(explains != null && explains.containsKey("appHide")) {
                        Integer appHide = explains.getInteger("appHide");
                        dataPojo.setAppHide(appHide);
                    } else {
                        dataPojo.setAppHide(BasicConstant.ONE);
                    }
                } else {
                    if (!categoryMap.containsKey(dataPojo.getChartCategoryId())) {
                        iterator.remove();
                        continue;
                    }
                    ChartCategoryEntity categoryEntity = categoryMap.get(dataPojo.getChartCategoryId());
                    // 分类处理
                    dataPojo.setSecondCategoryId(null);
                    dataPojo.setChartCategoryType(ChartConstant.CHART_CATEGORY_TYPE_CATEGORY);
                    dataPojo.setEnable(categoryEntity.getEnable());
                    dataPojo.setStatisticsType(StatisticsTypeEnum.SYSTEM_STATISTIC.getCode());

                    // 默认展示方式
                    ChartCategoryAliasEnum aliasEnum = ChartCategoryAliasEnum.getByAlias(categoryEntity.getAlias());
                    if (Objects.nonNull(aliasEnum)) {
                        dataPojo.setShowType(aliasEnum.getShowType());
                    }
                    // 排序
                    if (Objects.isNull(dataPojo.getSort())) {
                        dataPojo.setSort(BasicConstant.ZERO);
                    }
                    // 系统时设置为1，非隐藏
                    if (Objects.isNull(dataPojo.getAppHide())) {
                        dataPojo.setAppHide(BasicConstant.ONE);
                    }
                    handleChildList(dataPojo, allChartList, allCustomChartList, nonCompanyConfig);
                }
            }

            JSONArray data = new JSONArray();
            data.addAll(setDbList);
            setEntity.setContentData(data);
            long now = DateUtil.getInt();
            setEntity.setUpdateTime(now);
        }
        if (CollectionsUtil.isNotEmpty(list)) {
            try {
                indexSetModel.updateBatch(list, corpid);
            } catch (Exception e) {
                LOG.error("更新首页看板报错", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nMessageUtil.getMessage(ErrorMessageConstant.SAVE_ERROR));
            }
        }
    }

    /***
     * 清空首页看板设置：公司系统设置不能清空（userId=0）
     *
     * @param corpid 公司corpid
     * @param: list 首页看板设置
     * @throws
     * @return void
     * @author hongxiao
     * @date 2022-08-29 14:15
     * @since
     * @version
     */
    private void clearIndexSet(String corpid, List<IndexSetEntity> list) throws XbbException {

        // 更新的数据
        Iterator<IndexSetEntity> iterator = list.listIterator();
        long now = DateUtil.getInt();
        while (iterator.hasNext()) {
            IndexSetEntity setEntity = iterator.next();
            // 公司默认看板数据不清空
            if (Objects.equals(BasicConstant.ZERO_STRING, setEntity.getUserId())) {
                iterator.remove();
                continue;
            }
            setEntity.setContentData(new JSONArray());
            setEntity.setUpdateTime(now);
        }
        if (CollectionsUtil.isNotEmpty(list)) {
            indexSetModel.updateBatch(list, corpid);
        }
    }

    /***
     * 添加看板数据
     *
     * @param corpid 公司corpid
     * @param list 看板设置
     * @param addData 添加的数据
     * @throws
     * @return void
     * @author hongxiao
     * @date 2022-08-29 15:38
     * @since
     * @version
     */
    private void addIndexSet(String corpid, List<IndexSetEntity> list, Map<String, IndexSetAddContentPojo> addData) throws XbbException{
        if (Objects.isNull(addData) || addData.size() == 0) {
            return;
        }
        // 只包含看板
        boolean onlyParent = addData.size() == BasicConstant.ONE && addData.containsKey(BasicConstant.ZERO_STRING);
        // 添加外层及内容数据
        for (IndexSetEntity setEntity : list) {
            List<IndexSetDataPojo> setDbList = setEntity.getContentData().toJavaList(IndexSetDataPojo.class);
            if (addData.containsKey(BasicConstant.ZERO_STRING)) {
                IndexSetAddContentPojo addContentPojo = addData.get(BasicConstant.ZERO_STRING);
                setDbList.addAll(addContentPojo.getData());
            }
            if (!onlyParent) {
                // 添加看板下指标
                for (IndexSetDataPojo dataPojo : setDbList) {
                    // 只有分类才可添加指标
                    if (addData.containsKey(dataPojo.getChartCategoryId().toString()) && Objects.equals(dataPojo.getChartCategoryType(), ChartConstant.CHART_CATEGORY_TYPE_CATEGORY)) {
                        IndexSetAddContentPojo addContentPojo = addData.get(dataPojo.getChartCategoryId().toString());
                        dataPojo.setEnableList(addContentPojo.getEnableList());
                        dataPojo.setDisableList(addContentPojo.getDisableList());
                    }
                }
            }

            JSONArray data = new JSONArray();
            data.addAll(setDbList);
            setEntity.setContentData(data);
            long now = DateUtil.getInt();
            setEntity.setUpdateTime(now);
        }
        if (CollectionsUtil.isNotEmpty(list)) {
            indexSetModel.updateBatch(list, corpid);
        }
    }

    /***
     * 修复看板指标数据
     *
     * @param dataPojo 看板设置
     * @param: systemList 系统指标
     * @param: customList 自定义指标
     * @param nonCompanyConfigFlag 非公司配置
     * @throws
     * @return void
     * @author hongxiao
     * @date 2022-08-29 14:14
     * @since
     * @version
     */
    private void handleChildList(IndexSetDataPojo dataPojo, List<ChartEntity> systemList, List<ChartEntity> customList, boolean nonCompanyConfigFlag) {
        Long categoryId = dataPojo.getChartCategoryId();
        List<IndexBoardChartSavePojo> enableChildList = new ArrayList<>();
        List<IndexBoardChartSavePojo> disableChildList = new ArrayList<>();
        for (ChartEntity chartEntity : systemList) {
            List<Long> cidList = chartEntity.getCategory().toJavaList(Long.class);
            if (!cidList.contains(categoryId)) {
                continue;
            }
            // 非系统配置（userId!=0）只添加开启状态的指标
            if (nonCompanyConfigFlag && Objects.equals(BasicConstant.NO_USE, chartEntity.getEnable())) {
                continue;
            }
            IndexBoardChartSavePojo chartSavePojo = new IndexBoardChartSavePojo();
            chartSavePojo.setId(chartEntity.getId());
            chartSavePojo.setStatisticsType(chartEntity.getStatisticsType());
            chartSavePojo.setSort(BasicConstant.ZERO);
            if (Objects.equals(BasicConstant.IS_USE, chartEntity.getEnable())) {
                enableChildList.add(chartSavePojo);
            } else {
                disableChildList.add(chartSavePojo);
            }
        }
        for (ChartEntity chartEntity : customList) {
            List<Long> cidList = chartEntity.getCategory().toJavaList(Long.class);
            if (!cidList.contains(categoryId)) {
                continue;
            }
            // 非系统配置（userId!=0）只添加开启状态的指标
            if (nonCompanyConfigFlag && Objects.equals(BasicConstant.NO_USE, chartEntity.getEnable())) {
                continue;
            }
            IndexBoardChartSavePojo chartSavePojo = new IndexBoardChartSavePojo();
            chartSavePojo.setId(chartEntity.getId());
            chartSavePojo.setStatisticsType(chartEntity.getStatisticsType());
            chartSavePojo.setSort(BasicConstant.ZERO);
            if (Objects.equals(BasicConstant.IS_USE, chartEntity.getEnable())) {
                enableChildList.add(chartSavePojo);
            } else {
                disableChildList.add(chartSavePojo);
            }
        }

        dataPojo.getEnableList().clear();
        dataPojo.getDisableList().clear();

        // 设置最大启用个数
        int length = enableChildList.size();
        if (enableChildList.size() >= CHART_MAX_COUNT) {
            length = CHART_MAX_COUNT;
        }
        List<IndexBoardChartSavePojo> subChildList = enableChildList.subList(0, length);
        disableChildList.addAll(0, enableChildList.subList(length, enableChildList.size()));

        if (CollectionsUtil.isNotEmpty(subChildList)) {
            dataPojo.setEnableList(new ArrayList<>(subChildList));
        }
        if (CollectionsUtil.isNotEmpty(disableChildList)) {
            dataPojo.setDisableList(disableChildList);
        }
    }
}
